<template>
  <div class="app-container" id="app-main">
    <!-- 查询和其他操作 -->
    <div>
      <div class="filter-container">
        <el-input
          v-model="query.userName"
          clearable
          size="small"
          class="filter-item"
          style="width: 200px"
          :placeholder="$t('message.user.placeholder')"
          @keyup.enter="handleFind"
        />
        <!-- <el-select
          v-model="query.existOrg"
          class="filter-item-left"
          style="width: 200px"
          :placeholder="`${$t('message.validate.please_select')}`"
          size="small"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <!-- class="filter-item-right" -->
        <el-button icon="el-icon-search" size="small" @click="handleFind">{{
          $t('message.operate.search')
        }}</el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-refresh"
          size="small"
          @click="handleReset"
          >{{ $t('message.operate.reset') }}</el-button
        >
      </div>
      <div class="filter-container filter-container2">
        <el-button
          v-limit="'XTGL:YHGL:ADD'"
          class="filter-item"
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="handleAdd"
          >{{ $t('message.operate.add') }}</el-button
        >
        <!-- <NewImport v-limit="'XTGL:YHGL:IMPORT'"></NewImport> -->
        <el-button
          v-limit="'XTGL:YHGL:EXPORT'"
          class="filter-item"
          type="primary"
          size="small"
          @click="handleExport"
          >{{ $t('message.operate.export') }}</el-button
        >
        <!-- <el-button
          v-limit="'XTGL:YHGL:DOWNLOAD'"
          class="filter-item"
          type="primary"
          size="small"
          @click="handleTemplate"
          >{{ $t('message.operate.importTemplate') }}</el-button
        > -->
        <el-button
          v-limit="'XTGL:YHGL:SYNC'"
          class="filter-item"
          type="primary"
          size="small"
          @click="pullUsers"
        >
          同步用户数据
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :max-height="550"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- <el-table-column :label="$t('message.user.index')" width="60" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column> -->
      <el-table-column type="index" :index="indexMethod" align="center" label="序号" width="50" fixed="left" />

      <el-table-column :label="$t('message.user.name')" align="center">
        <template #default="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.user.cname')" width="100" align="center">
        <template #default="scope">
          <span>{{ scope.row.cname }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.user.phone')" align="center">
        <template #default="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.user.email')" width="180" align="center">
        <template #default="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.user.status')" align="center">
        <template #default="scope">
          <el-tag>{{ scope.row.lockFlag == 0 ? '正常' : '锁定' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.user.roles')" align="center" min-width="200">
        <template #default="scope">
          <div class="roles">
            <div v-for="item in scope.row.roleList" :key="item.roleId">
              <el-tag type="info">{{ item.roleName }}</el-tag>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.operate.operate')"
        fixed="right"
        min-width="200"
        align="center"
      >
        <template #default="scope">
          <!--<el-button @click="handRest(scope.row)" type="warning" size="small">重置密码</el-button>-->
          <el-button
            v-limit="'XTGL:YHGL:EDIT'"
            size="small"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            >{{ $t('message.operate.edit') }}</el-button
          >
          <el-button
            v-limit="'XTGL:YHGL:DELETE'"
            size="small"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(scope.row)"
            >{{ $t('message.operate.delete') }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="pagination">
      <el-pagination
        v-model="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        background
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog
      v-if="dialogFormVisible"
      v-model="dialogFormVisible"
      :title="operation ? $t('message.orgUser.addUser') : $t('message.user.editUser')"
      :width="dialogWidth"
      @close="onClose"
    >
      <el-form
        ref="form"
        :model="dataForm"
        :rules="rules"
        label-width="80px"
        size="small"
        :inline="true"
        label-position="right"
      >
        <el-form-item
          :label="$t('message.user.name')"
          :label-width="formLabelWidth"
          prop="username"
          required
        >
          <el-input
            v-model="dataForm.username"
            auto-complete="off"
            :placeholder="$t('message.validate.please_input_user')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('message.user.cname')"
          :label-width="formLabelWidth"
          prop="cname"
          required
        >
          <el-input
            v-model="dataForm.cname"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item :label="$t('message.user.email')" :label-width="formLabelWidth" prop="email">
          <el-input
            v-model="dataForm.email"
            auto-complete="off"
            :placeholder="$t('message.validate.input_email')"
          />
        </el-form-item>

        <el-form-item :label="$t('message.user.phone')" :label-width="formLabelWidth">
          <el-input
            v-model="dataForm.phone"
            auto-complete="off"
            :placeholder="$t('message.validate.input_phone')"
          />
        </el-form-item>
        <el-form-item label="所属公司:" :label-width="formLabelWidth" prop="orgname">
          <popup-tree-input
            :data="orgList"
            :props="deptTreeProps"
            :prop="dataForm.orgname"
            :current-change-handle="orgTreeCurrentChangeHandle"
          />
        </el-form-item>
        <el-form-item label="所属部门:" :label-width="formLabelWidth" prop="deptName">
          <popup-tree-input
            :data="depList"
            :props="deptTreeProps"
            :prop="dataForm.deptName"
            :current-change-handle="deptTreeCurrentChangeHandle"
          />
        </el-form-item>
        <el-form-item label="数据权限" label-width="120px" prop="dataPermissions">
          <el-select v-model="dataForm.dataPermissions" placeholder="请选择">
            <el-option
              v-for="item in permissionsList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('message.user.roles')"
          prop="roleList"
          style="width: 91%"
          label-width="120px"
        >
          <el-select
            v-model="dataForm.roleList"
            multiple
            :placeholder="$t('message.validate.please_select')"
            style="width: 100%"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <!-- 添加密码 -->
        <el-form-item :label="$t('message.user.password')" label-width="120px" prop="pass">
          <el-input
            v-model="dataForm.pass"
            type="password"
            autocomplete="off"
            placeholder="******"
          />
        </el-form-item>
        <el-form-item
          v-if="dataForm.pass"
          :label="$t('message.user.confirmPassword')"
          prop="checkPass"
          required
          label-width="120px"
        >
          <el-input v-model="dataForm.checkPass" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item :label="$t('message.user.status')" prop="lockFlag" label-width="120px">
          <el-switch
            class="radio"
            v-model="dataForm.lockFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-text="$t('message.user.normal')"
            active-value="0"
            :inactive-text="$t('message.user.lock')"
            inactive-value="1"
          />
        </el-form-item>
        <el-form-item label="学历" label-width="120px">
          <el-select v-model="dataForm.educationBackground" placeholder="请选择">
            <el-option
              v-for="item in dictList.EDUCATION"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemText"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="民族" label-width="120px">
          <el-select v-model="dataForm.nation" placeholder="请选择">
            <el-option
              v-for="item in dictList.NATIONALITYS"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemText"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="政治面貌" label-width="120px">
          <el-select v-model="dataForm.remark" placeholder="请选择">
            <el-option
              v-for="item in dictList.ZZMM"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemText"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职称" label-width="120px">
          <el-select v-model="dataForm.technicalTitle" placeholder="请选择">
            <el-option
              v-for="item in dictList.TITLE"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemText"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学位" label-width="120px">
          <el-input v-model="dataForm.degree" placeholder="请填写学位" />
        </el-form-item>
        <el-form-item label="技术领域" label-width="120px">
          <el-input v-model="dataForm.technology" placeholder="请填写技术领域" />
        </el-form-item>
        <el-form-item label="从事科研年限" label-width="120px">
          <el-input
            type="number"
            v-model="dataForm.scientificYears"
            placeholder="请填写从事科研年限"
          />
        </el-form-item>
      </el-form>
      <!-- footer -->
      <template #footer class="dialog-footer">
        <el-button @click="onClose">{{ $t('message.operate.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t('message.operate.confirm')
        }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import initDict from '@/mixins/initDict'
import { encryptionRSA } from '@/utils/encryption'
import { getAllOrgTree,getDeptByOrg } from '@/views/project/api/commom'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import { servicesLoading } from '@/views/project/project-manage/loading'
import { get } from 'lodash'
import { getOrg } from '../api/org'
import { getRoleList } from '../api/roles'
import { addUser, deleteUser, editUser, getUserDict, getUsers, pullUsers } from '../api/users'
import { exportMethod } from '../utils/exportData'
import { checkMobile } from '../utils/validate'
import NewImport from './components/newImport/index.vue'
import { ElMessage } from 'element-plus'

export default {
  components: {
    NewImport,
    PopupTreeInput,
  },
  mixins: [initDict],
  emits: ['close'],
  data() {
    return {
      // 用户列表
      tableData: [],
      roles: [], // 角色列表
      jobs: [], // 岗位列表
      operation: false, // true:新增, false:编辑
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总数量
      deptId: '',
      dialogFormVisible: false, // 控制弹出框
      formLabelWidth: '120px',
      query: {
        userName: '',
        existOrg: '',
      },
      dataForm: {
        username: '',
        cname: '', // 用户姓名
        avatar: '',
        orgId: '',
        orgname: '',
        deptId: '',
        deptName: '',
        dataPermissions: 1,
        email: '',
        phone: '',
        lockFlag: '' + 0,
        roleList: [],
        pass: '', // 用户密码
        checkPass: '', // 确认密码
        educationBackground: '', //学历
        nation: '', //民族
        remark: '', //政治面貌
        technicalTitle: '', //职称
        typeOfWork: '', //所属工种
        selectOrgs: '', //行政职务
        degree: '', //学位
        technology: '', //技术领域
        scientificYears: '', //从事科研年限
      },
      deptData: [],
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      value5: '100',
      filterText: '',
      loading: false,
      jobName: '',
      multipleSelection: [],
      dictList: [],
      orgList: [],
      depList: [],
      permissionsList: [
        {
          value: 0,
          name: '全部数据权限',
        },
        {
          value: 1,
          name: '本部门及以下数据权限',
        },
        {
          value: 2,
          name: '本部门数据权限',
        },
        {
          value: 3,
          name: '仅本人数据权限',
        },
      ],
    }
  },
  computed: {
    // ...mapGetters(['maxHeightTable', 'ismobile']),
    maxHeight() {
      return this.height - 158
    },
    options() {
      return [
        {
          label: this.$i18n.t('message.user.unassigned'),
          value: '0',
        },
        { label: this.$i18n.t('message.user.allocated'), value: '1' },
      ]
    },
    rules() {
      return {
        username: [
          { required: true, message: this.$i18n.t('message.validate.required') },
          {
            pattern: /^[a-zA-Z0-9_]{4,20}$/,
            message: this.$i18n.t('message.validate.user'),
          },
        ],
        cname: [{ required: true, message: this.$i18n.t('message.validate.required') }],
        phone: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error(this.$i18n.t('message.validate.input_phone')))
              } else if (!checkMobile(value)) {
                callback(new Error('手机号码不合法'))
              } else {
                callback()
              }
            },
            trigger: 'change',
            required: true,
          },
        ],
        orgname: [
          {
            required: true,
            message: '请选择所属公司',
          },
        ],
        deptName: [
          {
            required: true,
            message: '请选择所属部门',
          },
        ],
        dataPermissions: [
          {
            required: true,
            message: '请选择数据权限',
          },
        ],
        email: [
          { required: false, message: this.$i18n.t('message.validate.required') },
          {
            // eslint-disable-next-line no-useless-escape
            pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
            message: this.$i18n.t('message.validate.illegal_email'),
          },
        ],
        pass: [
          {
            validator: this.validatePass,
          },
        ],
        checkPass: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.dataForm.pass) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      }
    },
  },
  created() {
    this.adminList()
    this.findUserRoles()
    this.findDeptTree()
    // 加载数据字典
    this.getDict('用户状态')
    this.setDialogWidth()
    getDeptByOrg().then((res) => {
      this.depList = res.data.data
      console.log(this.depList,'getDeptByOrg');
    })
    getAllOrgTree().then((res) => {
      this.orgList = res.data.data
    })
  },
  mounted() {
    this.height = document.getElementById('app-main').offsetHeight

    // if (this.$store.state.projectCenter.orgList.length == 0) {
    //   getDeptByOrg().then((res) => {
    //     this.$store.state.projectCenter.orgList = res.data.data
    //     this.$store.state.projectCenter.orgDefaultExpandedKeys = res.data.data.map(
    //       (item) => item.id
    //     )
    //   })
    // }
    getUserDict().then((res) => {
      this.dictList = res.data.data
      console.log(this.dictList, 'this.dictList')
    })
  },
  methods: {
    setDialogWidth() {
      if (this.ismobile) {
        this.dialogWidth = '90%'
      } else {
        this.dialogWidth = '50%'
      }
    },
    validatePass(rule, value, callback) {
      try {
        if (value === '') {
          callback()
        } else {
          if (this.dataForm.checkPass !== '') {
            this.$refs.form.validateField('checkPass')
          }
          callback()
        }
      } catch (e) {
        console.error(e)
      }
    },
    indexMethod (index){
      return this.pageSize*(this.currentPage-1) +index+1
    },
    // 复选框
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 加载用户角色信息
    findUserRoles() {
      const params = new URLSearchParams()
      params.append('roleName', '')
      getRoleList(params).then((res) => {
        this.roles = res.data.data
      })
    },
    // 加载机构列表
    findDeptTree: function () {
      getOrg().then((res) => {
        this.deptData = res.data.data
      })
    },
    orgTreeCurrentChangeHandle(data) {
      console.log(data, 'orgTreeCurrentChangeHandle')
      this.dataForm.orgId = data.id
      this.dataForm.orgname = data.name
      this.dataForm.deptId = ''
      this.dataForm.deptName = ''
      const loading = servicesLoading({ fullscreen: true,text: '加载部门列表' })
      getDeptByOrg(this.dataForm.orgId).then((res) => {
        this.depList = res.data.data
        console.log(this.depList,'getDeptByOrg');
        loading.close()
      }).catch(()=>{
        loading.close()
      })
    },
    // 机构菜单树选中
    deptTreeCurrentChangeHandle(data) {
      console.log(data, 'deptTreeCurrentChangeHandle')
      this.dataForm.deptId = data.id
      this.dataForm.deptName = data.name
    },
    // 加载用户列表
    adminList() {
      this.loading = true
      const params = new URLSearchParams()
      params.append('current', this.currentPage)
      params.append('size', this.pageSize)
      params.append('deptId', this.deptId)
      params.append('username', this.query.userName)
      params.append('existOrg', this.query.existOrg)
      getUsers({
        username: this.query.userName,
        current: this.currentPage,
        size: this.pageSize,
      }).then((response) => {
        this.loading = false
        this.tableData = get(response, 'data.data.records', [])
        this.total = get(response, 'data.data.total', 0)
      })
    },
    handleFind() {
      this.adminList()
    },
    handleReset() {
      this.query = {
        userName: '',
      }
      this.adminList()
    },
    // 添加
    handleAdd() {
      this.dialogFormVisible = true
      this.operation = true
      this.dataForm.dataPermissions = 1
    },
    handleTemplate() {
      this.$confirm('确定下载导入模板吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const myTemplate = {
          method: 'post',
          url: '/user/downloadTemplate',
          fileName: '用户导入模板',
          data: [],
        }
        exportMethod(myTemplate)
      })
    },
    // 导出
    handleExport() {
      if (this.multipleSelection.length == 0) {
        ElMessage({
          message: '请勾选需要导出的用户',
          type: 'warning',
        })
      } else {
        this.$confirm('确定要导出选中的数据吗?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          this.Export(this.multipleSelection.map((item) => item.userId))
        })
      }
    },
    pullUsers() {
      this.$confirm('确定要同步中咨系统用户数据吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const loading = servicesLoading({ fullscreen: false })
        // 同步中咨用户数据
        pullUsers().then(() => {
          this.$message({
            type: 'success',
            message: '操作成功',
          })
          loading.close()
          this.adminList()
        })
      })
    },
    Export(dto) {
      const myDownload = {
        method: 'post',
        url: '/user/export',
        fileName: '用户数据导出',
        data: dto,
      }
      exportMethod(myDownload)
    },
    // 编辑
    handleEdit(row) {
      console.log(row, 'handleEdit')
      this.dialogFormVisible = true
      this.operation = false
      // this.dataForm = row
      this.dataForm = Object.assign({}, row)
      this.dataForm.jobId = row.jobId
      // this.getJobs(this.dataForm.jobId)
      // this.getJobs(row.jobId)

      // 设置选择的角色列表
      const userRoles = []
      for (let i = 0, len = row.roleList?.length; i < len; i++) {
        userRoles.push(row.roleList[i].roleId)
      }
      this.dataForm.roleList = userRoles
    },

    // 删除用户
    handleDelete(row) {
      const that = this
      this.$confirm('此操作将该管理员删除, 是否继续?', '提示', {
        confirmButtonText: this.$i18n.t('message.operate.confirm'),
        cancelButtonText: this.$i18n.t('message.operate.cancel'),
        type: 'warning',
      })
        .then(() => {
          deleteUser(row.userId).then((response) => {
            if (response.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功',
              })
              that.adminList()
            } else {
              this.$message({
                type: 'error',
                message: response.data.msg,
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.adminList()
    },
    onClose() {
      this.dialogFormVisible = false
      this.dataForm = {
        username: '',
        cname: '', // 用户姓名
        avatar: '',
        deptId: '',
        deptName: '',
        email: '',
        phone: '',
        lockFlag: '' + 0,
        roleList: [],
        pass: '', // 用户密码
        checkPass: '', // 确认密码
      }
    },
    handleNodeClick(data) {
      this.deptId = data.deptId === '' ? '' : data.deptId
      this.adminList()
    },
    submitForm() {
      const userRoles = []
      for (let i = 0, len = this.dataForm.roleList?.length; i < len; i++) {
        userRoles.push(this.dataForm.roleList[i])
      }
      this.dataForm.roleList = userRoles
      console.log(this.dataForm, 'this.dataForm')
      delete this.dataForm.password
      const params = this.dataForm.pass
        ? {
            ...this.dataForm,
            pass: undefined,
            password: encryptionRSA(this.dataForm.pass),
          }
        : {
            ...this.dataForm,
            pass: undefined,
          }
      if (!this.operation) {
        // 编辑用户
        this.$refs.form.validate((validate) => {
          if (validate) {
            const loading = servicesLoading()

            editUser(params)
              .then((response) => {
                loading.close()
                if (response.data.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '操作成功',
                  })
                  this.dialogFormVisible = false
                  this.adminList()
                } else {
                  this.$message({
                    type: 'error',
                    message: response.data.msg,
                  })
                }
              })
              .catch(() => {
                loading.close()
              })
          } else {
            ElMessage({
              message: '请将基本信息补充完整',
              type: 'warning',
            })
          }
        })
      } else {
        // 添加用户
        this.$refs.form.validate((validate) => {
          if (validate) {
            addUser(params).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功',
                })
                this.dialogFormVisible = false
                this.adminList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          }
        })
      }
    },
  },
}
</script>

<style scoped lang="scss">
.filter-item {
  margin-right: 10px;
}
.roles {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;

  & > div {
    margin-left: 10px;
    margin-top: 3px;
  }
}

.el-form {
  .el-form-item {
    width: 45%;
  }
  .el-form-item__label {
    width: 120px;
  }
}
.radio {
  display: flex;
  margin-top: 5px;
}
:deep(.el-form) {
  max-height: 500px;
  overflow-y: scroll;
}
</style>
